
//
//  SIEmoticonCell.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/13.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

@objc protocol SIEmoticonCellDelegate: NSObjectProtocol {

    func emoticonCellDidSelectedEmoticon(cell: SIEmoticonCell, em: SIEmoticon?)

}

class SIEmoticonCell: UICollectionViewCell {
    
    @IBOutlet weak var label: UILabel!
    
    weak var delegate: SIEmoticonCellDelegate?
    
    var emoticons: [SIEmoticon]? {
        
        didSet {
            for v in contentView.subviews {
                v.isHidden = true
            }
            
            contentView.subviews.last?.isHidden = false
            
            for (i, em) in (emoticons ?? []).enumerated() {

                if let btn = contentView.subviews[i] as? UIButton {
                    btn.setImage(em.image, for: [])
                    
                    btn.setTitle(em.emoji, for: [])
                    
                    btn.isHidden = false
                }
            }

            
        }
    }
    
    override func awakeFromNib() {
        setupUI()
    }
    /// 表情选择提示视图
    private lazy var tipView = SIEmoticonTipVIew()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else {
            
            return
        }
        
        w.addSubview(tipView)
        
        tipView.isHidden = true
        
    }
    
    // MARK: - 监听方法
    /// 选择表情按钮
    @objc private func selectedEmoticonButton(button: UIButton) {
        
        let tag = button.tag
        
        var em: SIEmoticon?
        
        if tag < emoticons?.count {
            em = emoticons?[tag]
        }
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
    }
    /// 表情cell的手势监听方法
    // MARK: - 表情cell的监听方法
    @objc private func longGesture(gesture: UILongPressGestureRecognizer) {
        
        let location = gesture.location(in: self)
        
        guard let button = buttonWithLocation(location: location) else {
            
            tipView.isHidden = true
            
            return
        }
        
        switch gesture.state {
        case .began, .changed:
            tipView.isHidden = false
            let center = self.convert(button.center, to: window)
            
            tipView.center = center
            
            if button.tag < emoticons?.count {
                tipView.emoticon = emoticons?[button.tag]
            }
        case .ended:
            tipView.isHidden = true
            
            selectedEmoticonButton(button: button)
            
        case .cancelled, .failed:
            tipView.isHidden = true
            
        default:
            break
        }
        
        print(button)
        
    }
    
    /// 点击的位置对应的button
    private func buttonWithLocation(location: CGPoint) -> UIButton? {
        
        for btn in contentView.subviews as! [UIButton] {
            
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last {
                return btn
            }
        }
        
        return nil
    }
    
}

private extension SIEmoticonCell {
    
    func setupUI() {
        let rowCount = 3
        let colCount = 7
        
        let leftMargin: CGFloat = 8
        let bottomMargin: CGFloat = 16
        
        let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
        let h = (bounds.height - bottomMargin) / CGFloat(rowCount)

        
        // 20个表情按钮, 一个删除按钮
        for i in 0..<21 {
            let row = i / colCount
            let col = i % colCount
            
            let btn = UIButton()
//            btn.backgroundColor = UIColor.red()
            
            let x = leftMargin + CGFloat(col) * w
            let y = CGFloat(row) * h
            
            btn.frame = CGRect(x: x, y: y, width: w, height: h)

            
            contentView.addSubview(btn)
            
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            btn.tag = i
            
            btn.addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside)
            
        }
        
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: SIEmotionManager.shared.bundle, compatibleWith: nil)
        
        (contentView.subviews.last as! UIButton).setImage(image, for: [])
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        
        longPress.minimumPressDuration = 0.1
        
        addGestureRecognizer(longPress)
        
    }

    
    
    
}
